#!/usr/bin/env bash

GET_BASE_PATH() {
    # Aria2下载目录
    DOWNLOAD_PATH="/downloads"
    # 种子备份目录
    BAK_TORRENT_DIR="/config/backup-torrent"
    # 日志、配置文件保存路径
    SCRIPT_CONF="/config/文件过滤.conf"
    CF_LOG="/config/logs/文件过滤日志.log"
    MOVE_LOG="/config/logs/move.log"
    DELETE_LOG="/config/logs/delete.log"
    RECYCLE_LOG="/config/logs/recycle.log"
}

# ========================GET_TARGET_PATH==============================

COMPLETED_PATH() {
    # 完成任务后转移
    TARGET_DIR="${DOWNLOAD_PATH}/completed"
}

RECYCLE_PATH() {
    # 回收站
    TARGET_DIR="${DOWNLOAD_PATH}/recycle"
}

# ============================颜色==============================

RED_FONT_PREFIX="\033[31m"
LIGHT_GREEN_FONT_PREFIX="\033[1;32m"
YELLOW_FONT_PREFIX="\033[1;33m"
LIGHT_PURPLE_FONT_PREFIX="\033[1;35m"
FONT_COLOR_SUFFIX="\033[0m"
INFO="[${LIGHT_GREEN_FONT_PREFIX}INFO${FONT_COLOR_SUFFIX}]"
ERROR="[${RED_FONT_PREFIX}ERROR${FONT_COLOR_SUFFIX}]"
WARRING="[${YELLOW_FONT_PREFIX}WARRING${FONT_COLOR_SUFFIX}]"

# ============================时间==============================

DATE_TIME() {
    date +"%Y/%m/%d %H:%M:%S"
}

# ==========================任务信息===============================

TASK_INFO() {
    echo -e "
-------------------------- [${YELLOW_FONT_PREFIX} 任务信息 ${TASK_TYPE} ${FONT_COLOR_SUFFIX}] --------------------------
${LIGHT_PURPLE_FONT_PREFIX}根下载路径:${FONT_COLOR_SUFFIX} ${DOWNLOAD_PATH}
${LIGHT_PURPLE_FONT_PREFIX}任务位置:${FONT_COLOR_SUFFIX} ${SOURCE_PATH}
${LIGHT_PURPLE_FONT_PREFIX}首个文件位置:${FONT_COLOR_SUFFIX} ${FILE_PATH}
${LIGHT_PURPLE_FONT_PREFIX}任务文件数量:${FONT_COLOR_SUFFIX} ${FILE_NUM}
${LIGHT_PURPLE_FONT_PREFIX}移动至目标文件夹:${FONT_COLOR_SUFFIX} ${TARGET_PATH}
-----------------------------------------------------------------------------------------------------------------------
"
}

DELETE_INFO() {
    echo -e "
-------------------------- [${YELLOW_FONT_PREFIX} 任务信息 ${TASK_TYPE} ${FONT_COLOR_SUFFIX}] --------------------------
${LIGHT_PURPLE_FONT_PREFIX}根下载路径:${FONT_COLOR_SUFFIX} ${DOWNLOAD_PATH}
${LIGHT_PURPLE_FONT_PREFIX}任务位置:${FONT_COLOR_SUFFIX} ${SOURCE_PATH}
${LIGHT_PURPLE_FONT_PREFIX}首个文件位置:${FONT_COLOR_SUFFIX} ${FILE_PATH}
${LIGHT_PURPLE_FONT_PREFIX}任务文件数量:${FONT_COLOR_SUFFIX} ${FILE_NUM}
-----------------------------------------------------------------------------------------------------------------------
"
}

# =============================读取conf文件设置=============================

LOAD_SCRIPT_CONF() {
    MIN_SIZE="$(grep ^min-size "${SCRIPT_CONF}" | cut -d= -f2-)"
    INCLUDE_FILE="$(grep ^include-file "${SCRIPT_CONF}" | cut -d= -f2-)"
    EXCLUDE_FILE="$(grep ^exclude-file "${SCRIPT_CONF}" | cut -d= -f2-)"
    KEYWORD_FILE="$(grep ^keyword-file "${SCRIPT_CONF}" | cut -d= -f2-)"
    INCLUDE_FILE_REGEX="$(grep ^include-file-regex "${SCRIPT_CONF}" | cut -d= -f2-)"
    EXCLUDE_FILE_REGEX="$(grep ^exclude-file-regex "${SCRIPT_CONF}" | cut -d= -f2-)"
}

DELETE_EXCLUDE_FILE() {
    if [[ ${FILE_NUM} -gt 1 ]] && [ "${SOURCE_PATH}" != "${DOWNLOAD_PATH}" ] && [[ -n ${MIN_SIZE} || -n ${INCLUDE_FILE} || -n ${EXCLUDE_FILE} || -n ${KEYWORD_FILE} || -n ${EXCLUDE_FILE_REGEX} || -n ${INCLUDE_FILE_REGEX} ]]; then
        echo -e "$(DATE_TIME) ${INFO} 删除不需要的文件..."
        [[ -n ${MIN_SIZE} ]] && find "${SOURCE_PATH}" -type f -size -${MIN_SIZE} -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
        [[ -n ${EXCLUDE_FILE} ]] && find "${SOURCE_PATH}" -type f -regextype posix-extended -iregex ".*\.(${EXCLUDE_FILE})" -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
        [[ -n ${KEYWORD_FILE} ]] && find "${SOURCE_PATH}" -type f -regextype posix-extended -iregex ".*(${KEYWORD_FILE}).*" -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
        [[ -n ${INCLUDE_FILE} ]] && find "${SOURCE_PATH}" -type f -regextype posix-extended ! -iregex ".*\.(${INCLUDE_FILE})" -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
        [[ -n ${EXCLUDE_FILE_REGEX} ]] && find "${SOURCE_PATH}" -type f -regextype posix-extended -iregex "${EXCLUDE_FILE_REGEX}" -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
        [[ -n ${INCLUDE_FILE_REGEX} ]] && find "${SOURCE_PATH}" -type f -regextype posix-extended ! -iregex "${INCLUDE_FILE_REGEX}" -print0 | xargs -0 rm -vf | tee -a ${CF_LOG}
    fi
}

# =============================删除.ARIA2=============================

RM_ARIA2() {
    if [ -e "${SOURCE_PATH}.aria2" ]; then
        rm -f "${SOURCE_PATH}.aria2"
        echo -e "$(DATE_TIME) ${INFO} 已删除文件: ${SOURCE_PATH}.aria2"
    fi
}

# =============================删除空文件夹=============================

DELETE_EMPTY_DIR() {
    if [ "${DET}" = "true" ]; then
        echo -e "$(DATE_TIME) ${INFO} 删除任务中空的文件夹 ..."
        find "${SOURCE_PATH}" -depth -type d -empty -exec rm -vrf {} \;
    fi
}

# =============================内容过滤=============================

CLEAN_UP() {
    RM_ARIA2
    if [ "$CF" == "true" ] && [ ${FILE_NUM} -gt 1 ] && [ "${SOURCE_PATH}" != "${DOWNLOAD_PATH}" ]; then
        echo -e "$(DATE_TIME) ${INFO} 被过滤文件的任务路径: ${SOURCE_PATH}" | tee -a ${CF_LOG}
        LOAD_SCRIPT_CONF
        DELETE_EXCLUDE_FILE
        DELETE_EMPTY_DIR
    fi
}

# =============================移动文件=============================

MOVE_FILE() {
    # DOWNLOAD_DIR = DOWNLOAD_PATH，说明为在根目录下载的单文件，`dmof时不进行移动
    if [ "${MOVE}" = "false" ]; then
        RM_ARIA2
        return
    elif [ "${MOVE}" = "dmof" ] && [ "${DOWNLOAD_DIR}" = "${DOWNLOAD_PATH}" ] && [ ${FILE_NUM} -eq 1 ]; then
        RM_ARIA2
        return
    elif [ "${MOVE}" = "true" ] || [ "${MOVE}" = "dmof" ]; then
        TASK_TYPE=": 移动任务文件"
        TASK_INFO
        CLEAN_UP
        echo -e "$(DATE_TIME) ${INFO} 开始移动该任务文件到: ${LIGHT_GREEN_FONT_PREFIX}${TARGET_PATH}${FONT_COLOR_SUFFIX}"
        mkdir -p "${TARGET_PATH}"
        mv -f "${SOURCE_PATH}" "${TARGET_PATH}"
        MOVE_EXIT_CODE=$?
        if [ ${MOVE_EXIT_CODE} -eq 0 ]; then
            echo -e "$(DATE_TIME) ${INFO} 已移动文件至目标文件夹: ${SOURCE_PATH} -> ${TARGET_PATH}"
            [ ${MOVE_LOG} ] && echo -e "$(DATE_TIME) [INFO] 已移动文件至目标文件夹: ${SOURCE_PATH} -> ${TARGET_PATH}" >>${MOVE_LOG}
        else
            echo -e "$(DATE_TIME) ${ERROR} 文件移动失败: ${SOURCE_PATH}"
            [ ${MOVE_LOG} ] && echo -e "$(DATE_TIME) [ERROR] 文件移动失败: ${SOURCE_PATH}" >>${MOVE_LOG}
        fi
    fi
}

# =============================删除文件=============================

DELETE_FILE() {
    TASK_TYPE=": 删除任务文件"
    DELETE_INFO
    echo -e "$(DATE_TIME) ${INFO} 下载已停止，开始删除文件..."
    rm -rf "${SOURCE_PATH}"
    MOVE_EXIT_CODE=$?
    if [ ${MOVE_EXIT_CODE} -eq 0 ]; then
        echo -e "$(DATE_TIME) ${INFO} 已删除文件: ${SOURCE_PATH}"
        [ ${DELETE_LOG} ] && echo -e "$(DATE_TIME) [INFO] 文件删除成功: ${SOURCE_PATH}" >>${DELETE_LOG}
    else
        echo -e "$(DATE_TIME) ${ERROR} delete failed: ${SOURCE_PATH}"
        [ ${DELETE_LOG} ] && echo -e "$(DATE_TIME) [ERROR] 文件删除失败: ${SOURCE_PATH}" >>${DELETE_LOG}
    fi
}

# =============================回收站=============================

MOVE_RECYCLE() {
    TASK_TYPE=": 移动任务文件至回收站"
    TASK_INFO
    echo -e "$(DATE_TIME) ${INFO} 开始移动已下载的任务至回收站 ${LIGHT_GREEN_FONT_PREFIX}${TARGET_PATH}${FONT_COLOR_SUFFIX}"
    mkdir -p "${TARGET_PATH}"
    mv -f "${SOURCE_PATH}" "${TARGET_PATH}"
    MOVE_EXIT_CODE=$?
    if [ ${MOVE_EXIT_CODE} -eq 0 ]; then
        echo -e "$(DATE_TIME) ${INFO} 已移至回收站: ${SOURCE_PATH} -> ${TARGET_PATH}"
        [ ${RECYCLE_LOG} ] && echo -e "$(DATE_TIME) [INFO] 成功移动文件到回收站: ${SOURCE_PATH} -> ${TARGET_PATH}" >>${RECYCLE_LOG}
    else
        echo -e "$(DATE_TIME) ${ERROR} 移动文件到回收站失败: ${SOURCE_PATH}"
        echo -e "$(DATE_TIME) ${INFO} 已删除文件: ${SOURCE_PATH}"
        rm -rf "${SOURCE_PATH}"
        [ ${RECYCLE_LOG} ] && echo -e "$(DATE_TIME) [ERROR] 移动文件到回收站失败: ${SOURCE_PATH}" >>${RECYCLE_LOG}
    fi
}

# =============================处理种子文件=============================

HANDLE_TORRENT() {
    if [ "${TOR}" = "retain" ]; then
        return
    elif [ "${TOR}" = "delete" ]; then
        echo -e "$(DATE_TIME) ${INFO} 已删除种子文件: ${TORRENT_FILE}"
        rm -f "${TORRENT_FILE}"
        return
    elif [ "${TOR}" = "rename" ]; then
        echo -e "$(DATE_TIME) ${INFO} 已删除种子文件: ${TORRENT_FILE}"
        mv -f "${TORRENT_FILE}" "${TASK_NAME}.torrent"
    elif [ "${TOR}" = "backup" ]; then
        echo -e "$(DATE_TIME) ${INFO} 备份种子文件: ${TORRENT_FILE}"
        mv -vf "${TORRENT_FILE}" "${BAK_TORRENT_DIR}"
    elif [ "${TOR}" = "backup-rename" ]; then
        echo -e "$(DATE_TIME) ${INFO} 重命名并备份种子文件: ${BAK_TORRENT_DIR}/${TASK_NAME}.torrent"
        mv -f "${TORRENT_FILE}" "${BAK_TORRENT_DIR}/${TASK_NAME}.torrent"
    fi
}

CHECK_TORRENT() {
    if [ -e "${TORRENT_FILE}" ]; then
        HANDLE_TORRENT
    fi
}

# =============================判断文件路径=============================

GET_TARGET_PATH() {
    RELATIVE_PATH="${SOURCE_PATH#"${DOWNLOAD_PATH}/"}"
    TARGET_PATH="${TARGET_DIR}/$(dirname "${RELATIVE_PATH}")"
    # 出现 // 说明路径获取失败，为防止后续操作继续执行返回 error
    if [ "${TARGET_PATH}" == "${TARGET_DIR}//" ]; then
        GET_PATH_INFO="error"
        return
    # /downloads根目录下载会出现 /.
    elif [ "${TARGET_PATH}" = "${TARGET_DIR}/." ]; then
        TARGET_PATH="${TARGET_DIR}"
    fi
}

GET_FINAL_PATH() { 
    if [ -z "${FILE_PATH}" ]; then
        return
    # 判断是否为在文件夹内的单文件BT下载任务（会出现移动文件后文件夹保留的情况），如果是则降级到目录
    # 修复Mac下能够正常运行，Linux下失败的问题
    elif [ "${FILE_NUM}" -gt 1 ] || [ "$(dirname "${FILE_PATH}")" != "${DOWNLOAD_DIR}" ]; then
        RELATIVE_PATH="${FILE_PATH#"${DOWNLOAD_DIR}/"}"
        TASK_NAME="${RELATIVE_PATH%%/*}"
        SOURCE_PATH="${DOWNLOAD_DIR}/${TASK_NAME}"
        GET_TARGET_PATH
        COMPLETED_DIR="${TARGET_PATH}/${TASK_NAME}"
        return
    elif [ "${FILE_NUM}" -eq 1 ]; then
        SOURCE_PATH="${FILE_PATH}"
        RELATIVE_PATH="${FILE_PATH#"${DOWNLOAD_DIR}/"}"
        # 单文件，去除.
        TASK_NAME="${RELATIVE_PATH%.*}"
        GET_TARGET_PATH
        return
    fi
}
